﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using MINERP.BLL.GoodsDelivery;
using MINERP.MODEL.GoodsDelivery;
using MINERP.COM;

namespace ERPGoodsDelivery.Delivery
{
    public partial class FrmDeliverBack : Form
    {
        //属性
        private static FrmDeliverBack _instance;
        public static FrmDeliverBack GetInstance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new FrmDeliverBack();
                }
                return _instance;
            }
            set
            {
                _instance = value;
            }
        }
        //参数
        private DeliverBackBLL bll = new DeliverBackBLL();
        private BaseInfoBLL baseBll = new BaseInfoBLL();
        private DeliverFindBLL findBll = new DeliverFindBLL();

        //int
        int CurrentDeliverId;                                   //当前反馈的deliverId
        //int CurrentBillId;                                      //当前反馈的billId
        int model = 0;                                          //操作模式 0新增模式  1修改模式

        //List
        List<int> ModifiedBillIds = new List<int>();            //保存已修改过的BillId

        public FrmDeliverBack()
        {
            InitializeComponent();
        }

        //load
        private void FrmDeliverBack_Load(object sender, EventArgs e)
        {
            try
            {
                BindStation();
                BindStationGoods();
                BindReceiveStation();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //发货单号查询
        private void tsDeliverFind_Click(object sender, EventArgs e)
        {
            FindBillsByDeliver();
        }

        //保存发货单信息
        private void tsSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentDeliverId == 0)
                {
                    MessageBox.Show("不存在有效的发货单号！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                List<DeliveryBack> backs = gcBillInfoHeap.DataSource as List<DeliveryBack>;
                bool isContinue = true;
                foreach (DeliveryBack back in backs)
                {
                    if (back.IsModified == false)
                    {
                        if (DialogResult.Yes != (MessageBox.Show("还有未反馈的账单，任然要提交吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)))
                        {
                            isContinue = false;
                        }
                        break;
                    }
                }
                if (isContinue == false)
                {
                    return;
                }
                if (DialogResult.Yes == MessageBox.Show("确定要保持发货单信息吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    try
                    {
                        Cursor = Cursors.WaitCursor;
                        int deliverStatus = (int)DeliveryStatus.Deliverred;
                        bll.ChangeDeliveryToDeliver(CurrentDeliverId, deliverStatus);
                        MessageBox.Show("发货单信息保存成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        gcBillInfoHeap.DataSource = null;
                        gcBillInfoHeap.RefreshDataSource();
                        Cursor = Cursors.Default;
                    }
                    catch
                    {
                        Cursor = Cursors.Default;
                        MessageBox.Show("存在不正确的信息，不能保存！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //Enter键查询
        private void tsDeliverId_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                FindBillsByDeliver();
            }
        }

        //保存当前产品的发货信息
        private void tsSaveBill_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvBillInfoHeap.SelectedRowsCount == 0)
                {
                    MessageBox.Show("没有账单被选中！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                List<int> billIds = new List<int>();
                int[] indexes = gvBillInfoHeap.GetSelectedRows();
                foreach (int i in indexes)
                {
                    DeliveryBack back = gvBillInfoHeap.GetRow(i) as DeliveryBack;
                    back.IsModified = true;
                    int billId = back.BillId;
                    billIds.Add(billId);
                    if (!ModifiedBillIds.Contains(billId))
                    {
                        ModifiedBillIds.Add(billId);
                    }
                }
                Cursor = Cursors.WaitCursor;
                DateTime deliverTime = dtDeliverTime.Value;
                DateTime arrivalTime = dtArrivalTime.Value;
                string deliverObject = cbDeliverObject.Text;
                string TuoYunDanCode = txtTuoYunDanCode.Text;
                int num = Convert.ToInt16(spinNum.Text);
                double shopMoney = 0;
                if (txtShopMoney.Text != null && txtShopMoney.Text.Length > 0)
                    shopMoney = Convert.ToDouble(txtShopMoney.Text);
                double selfMoney = 0;
                if (txtSelfMoney.Text != null && txtSelfMoney.Text.Length > 0)
                    selfMoney = Convert.ToDouble(txtSelfMoney.Text);
                double otherMoney = 0;
                if (txtOtherMoney.Text != null && txtOtherMoney.Text.Length > 0)
                    otherMoney = Convert.ToDouble(txtOtherMoney.Text);
                string billRemark = txtRemark.Text;
                string stationRemark = cbStationRemark.Text;
                string receiveStationRemark = cbReceiveStation.Text;
                bll.SaveBillDeliverInfo(billIds, deliverTime, arrivalTime, deliverObject, TuoYunDanCode, num, stationRemark, shopMoney, selfMoney, otherMoney, billRemark, receiveStationRemark);

                //重新绑定数据
                FindBillsByDeliver();
                FocusBill(billIds[0]);
                //自动送信
                if (cbEmail.Checked)
                    AutoSendMail();
                MessageBox.Show("保存成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //单击显示当前账单的发货反馈信息
        private void gvBillInfoHeap_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            try
            {
                if (model == 1)             //修改模式：选中某个账单，下面需显示明细
                {
                    SetBillDetail(e.RowHandle);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //当前账单的发货反馈信息
        private void gvBillInfoHeap_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (model == 1)             //修改模式：选中某个账单，下面需显示明细
                {
                    SetBillDetail(e.FocusedRowHandle);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //操作模式
        private void tsModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (tsModel.Text == "添加模式")
                {
                    model = 0;                                      //表示新增
                    //gvBillInfoHeap.OptionsSelection.MultiSelect = true;
                    gvBillInfoHeap.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.RowSelect;
                }
                else if (tsModel.Text == "修改模式")
                {
                    model = 1;                                      //表示修改
                    //gvBillInfoHeap.OptionsSelection.MultiSelect = false;
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //背景色
        private void gvBillInfoHeap_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            try
            {
                if (e.RowHandle < 0)
                    return;
                DeliveryBack back = gvBillInfoHeap.GetRow(e.RowHandle) as DeliveryBack;
                if (back.IsModified == false)
                {
                    e.Appearance.BackColor = Color.Pink;
                    e.Appearance.BackColor2 = Color.Pink;
                }
                else
                {
                    e.Appearance.BackColor = Color.Empty;
                    e.Appearance.BackColor2 = Color.Empty;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //刷新客运站，货运站及其电话
        private void tsRefreshBase_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                BindStation();
                BindStationGoods();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //账单取消发货
        private void tsCancelDeliver_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvBillInfoHeap.SelectedRowsCount == 0)
                {
                    MessageBox.Show("没有账单被选中！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (DialogResult.Yes == MessageBox.Show("确定要取消选中的账单吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    Cursor = Cursors.WaitCursor;
                    List<int> billIds = new List<int>();
                    int[] indexes = gvBillInfoHeap.GetSelectedRows();
                    foreach (int index in indexes)
                    {
                        DeliveryBack back = gvBillInfoHeap.GetRow(index) as DeliveryBack;
                        billIds.Add(back.BillId);
                    }
                    bll.CancelBills(billIds);
                    FindBillsByDeliver();
                    Cursor = Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //-------------------------------公共方法-----------------------------------------
        #region 刚保存完的账单获得焦点
        /// <summary>
        /// 刚保存完的账单获得焦点
        /// </summary>
        /// <param name="billId"></param>
        private void FocusBill(int billId)
        {
            try
            {
                for (int i = 0; i < gvBillInfoHeap.RowCount; i++)
                {
                    if (billId == Convert.ToInt32(gvBillInfoHeap.GetRowCellValue(i, "BillId")))
                    {
                        gvBillInfoHeap.FocusedRowHandle = i;
                        break;
                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 绑定账单
        private void BindDeliverHeap(List<DeliveryBack> billInfos)
        {
            try
            {
                gcBillInfoHeap.DataSource = billInfos;
                gcBillInfoHeap.RefreshDataSource();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 设置账单是否已被修改
        /// <summary>
        /// 设置账单是否已被修改
        /// </summary>
        /// <param name="billInfos"></param>
        private void SetModified(List<DeliveryBack> billInfos)
        {
            try
            {
                foreach (DeliveryBack bill in billInfos)
                {
                    if (ModifiedBillIds.Contains(bill.BillId))
                    {
                        bill.IsModified = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 根据deliverId查询账单
        /// <summary>
        /// 根据deliverId查询账单
        /// </summary>
        private void FindBillsByDeliver()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                int deliverId = 0;
                try
                {
                    deliverId = Convert.ToInt32(tsDeliverId.Text);
                }
                catch
                {
                    MessageBox.Show("请输入正确的发货单号", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    CurrentDeliverId = 0;
                    tsDeliverId.Focus();
                    tsDeliverId.SelectAll();
                }
                CurrentDeliverId = deliverId;
                int printedStatus = (int)DeliveryStatus.Printed;
                List<DeliveryBack> billInfos = bll.GetBillsByDeliverIdAndStatus(deliverId, printedStatus);
                SetModified(billInfos);
                BindDeliverHeap(billInfos);
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 设置账单反馈的详情
        /// <summary>
        /// 设置账单反馈的详情
        /// </summary>
        /// <param name="index"></param>
        private void SetBillDetail(int index)
        {
            try
            {
                DeliveryBack back = gvBillInfoHeap.GetRow(index) as DeliveryBack;
                DateTime deliverTime = back.DeliverTime;
                if (deliverTime.Year < dtDeliverTime.MinDate.Year || deliverTime.Year > dtDeliverTime.MaxDate.Year)
                {
                    dtDeliverTime.Value = DateTime.Now;
                }
                else
                {
                    dtDeliverTime.Value = back.DeliverTime;
                }
                DateTime arrivalTime = back.ArrivalTime;
                if (arrivalTime.Year < dtArrivalTime.MinDate.Year || arrivalTime.Year > dtArrivalTime.MaxDate.Year)
                {
                    dtArrivalTime.Value = DateTime.Now;
                }
                else
                {
                    dtArrivalTime.Value = back.ArrivalTime;
                }
                cbDeliverObject.Text = back.DeliverObject;
                txtTuoYunDanCode.Text = back.TuoYunDanCode;
                spinNum.Value = back.Num;
                cbStationRemark.Text = back.StationRemark;
                cbReceiveStation.Text = back.ReceiveStationRemark;
                txtShopMoney.Text = string.Format("{0:0.##}", back.ShopMoney);
                txtSelfMoney.Text = string.Format("{0:0.##}", back.SelfMoney);
                txtOtherMoney.Text = string.Format("{0:0.##}", back.OtherMoney);
                txtRemark.Text = back.Remark;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 绑定客运站
        /// <summary>
        /// 绑定客运站
        /// </summary>
        private void BindStation()
        {
            try
            {
                List<BaseInfoBLL.StationInfo> stations = baseBll.GetStationInfo();
                cbDeliverObject.DisplayMember = "StationName";
                cbDeliverObject.ValueMember = "StationId";
                cbDeliverObject.DataSource = stations;
                cbDeliverObject.Text = "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 绑定货运站及其电话
        /// <summary>
        /// 绑定货运站及其电话
        /// </summary>
        private void BindStationGoods()
        {
            try
            {
                List<BaseInfoBLL.StationGoodsInfo> stationGoods = baseBll.GetStationGoodsInfo();
                cbStationRemark.DisplayMember = "StationGoodsNamePhone";
                cbStationRemark.ValueMember = "StationGoodsId";
                cbStationRemark.DataSource = stationGoods;
                cbStationRemark.Text = "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        private void BindReceiveStation()
        {
            try
            {
                List<BaseInfoBLL.ReceiveStation> stations = baseBll.GetReceiveStation();
                cbReceiveStation.DisplayMember = "StationNamePhone";
                cbReceiveStation.ValueMember = "ReceiveStationId";
                cbReceiveStation.DataSource = stations;
                cbReceiveStation.Text = "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 自动发邮件
        /// </summary>
        private void AutoSendMail()
        {
            try
            {
                if (gvBillInfoHeap.DataSource != null)
                {
                    //邮件报表包括2部分 1发货头信息 2账单内产品信息
                    //1头信息
                    DeliveryBack back = gvBillInfoHeap.GetRow(gvBillInfoHeap.GetSelectedRows()[0]) as DeliveryBack;
                    DataTable deliverTitle = bll.CreateDeliverBillInfo();
                    DataRow nr = deliverTitle.NewRow();
                    nr["ArrivalTime"] = back.ArrivalTime;
                    nr["BillId"] = back.BillId;
                    nr["BillIndexId"] = back.BillOrderCode;    //这里要注意
                    nr["DeliverId"] = back.DeliverId;
                    nr["DeliverObject"] = back.DeliverObject;
                    nr["DeliverTime"] = back.DeliverTime;
                    nr["Num"] = back.Num;
                    nr["OtherMoney"] = back.OtherMoney;
                    nr["ReceiveStationRemark"] = back.ReceiveStationRemark;
                    nr["SelfMoney"] = back.SelfMoney;
                    nr["ShopMoney"] = back.ShopMoney;
                    nr["StationRemark"] = back.StationRemark;
                    nr["TuoYunDanCode"] = back.TuoYunDanCode;
                    deliverTitle.Rows.Add(nr);
                    deliverTitle.TableName = "deliverTitle";


                    //2产品信息
                    List<DeliverFindBLL.OrderInfoCL> infos = findBll.GetOrderProductByBillId(back.BillId);
                    FastReport.Report report = new FastReport.Report();
                    DataTable dt = findBll.CreateOutDt();
                    foreach (DeliverFindBLL.OrderInfoCL info in infos)
                    {
                        DataRow nrr = dt.NewRow();
                        nrr["CtmName"] = info.CtmName;
                        nrr["OrderProductCode"] = info.OrderProductCode;
                        nrr["OrderProductName"] = info.OrderProductName;
                        dt.Rows.Add(nrr);
                    }
                    dt.TableName = "deliverOrderInfo";
                    DataSet ds = new DataSet();
                    ds.Tables.Add(deliverTitle);
                    ds.Tables.Add(dt);

                    //导出

                    ds.WriteXml(@"C:\WINDOWS\xmlData\deliverOrderInfos.xml", XmlWriteMode.WriteSchema);
                    int shopId = back.ShopId;

                    report.Load(Application.StartupPath + "\\deliverOrderInfo.frx");
                    //report.RegisterData(dt, "deliverOrderInfo");
                    report.Prepare();
                    FastReport.Export.Xml.XMLExport export = new FastReport.Export.Xml.XMLExport();
                    export.AllowOpenAfter = false;
                    report.Export(export, @"C:\WINDOWS\xmlData\deliverTemp.xls");                   //导出临时邮件文件
                    //发送
                    string shopMailAddr = findBll.GetShopMailAddr(shopId);
                    string sendMailAddr = Properties.Settings.Default.userSendBoxAddress;
                    string smtpServer = Properties.Settings.Default.userSmtpServer;
                    string pwd = Properties.Settings.Default.userPwd;
                    string title = Properties.Settings.Default.userTitle;
                    string content = Properties.Settings.Default.userContent;
                    string UserName = Properties.Settings.Default.UserName;
                    string attachMent = @"C:\WINDOWS\xmlData\deliverTemp.xls";                      //附件

                    string[] sends = sendMailAddr.Split('@');
                    SmtpClient client = new SmtpClient(smtpServer);
                    client.UseDefaultCredentials = false;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.Credentials = new NetworkCredential(UserName, pwd);
                    MailMessage mmsg = new MailMessage(sendMailAddr, shopMailAddr);
                    mmsg.Subject = title;
                    mmsg.SubjectEncoding = Encoding.UTF8;
                    mmsg.Body = content;
                    mmsg.BodyEncoding = Encoding.UTF8;
                    mmsg.IsBodyHtml = true;
                    mmsg.Priority = MailPriority.High;
                    mmsg.Attachments.Add(new Attachment(attachMent));
                    try
                    {
                        client.Send(mmsg);
                        //MessageBox.Show("邮件发送成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    mmsg.Dispose();
                    report.Dispose();

                }
                else
                {
                    MessageBox.Show("没有数据存在！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


    }
}
